/**
 * 作者：陈文斌 on 2019/1/16.
 * 邮箱：chen_wennbin@163.com
 * 版本：v1.0
 */

import 'package:crm/tools/apollo_util.dart';
import 'package:crm/model/VisitorRecord/visitor_type_model.dart';
import 'package:crm/model/VisitorRecord/visitor_record_model.dart';

class VisitorRecordVM {
  /// 查询拜访记录
  searchVisitorRecord(
    int page,
    List<VisitorRecordModel> visitorRecords, {
    String customerId,
    Function callback,
    Function errorCallback,
  }) {
    final int _take = 10; // 每次请求10条信息
    final int _skip = page * _take; // 从第skip + 1条开始请求
    bool _isMore = true;

    Map args = {
      'skip': '${_skip}',
      'take': '$_take',
    };
    if(customerId != null && customerId.isNotEmpty){
      args['customerId'] = customerId;
    }

    ApolloRequestUtil.searchVisitor(
          (response) {
        // 请求成功回调
        var _result = response['data']['crmVisitors']['items'];
        if (page == 0) visitorRecords = List<VisitorRecordModel>();
        for (var newsItem in _result) {
          visitorRecords.add(VisitorRecordModel.fromJson(newsItem));
        }

        _isMore = _result.length == _take;

        if (callback != null) {
          callback(visitorRecords, _isMore);
        }
      },
      args: args,
      errorCallback: (errMsg) {
        // 请求失败
        if (errorCallback != null) {
          errorCallback(errMsg);
        }
      },
    );
  }

  /// 获取访问类型
  getVisitorTypes({
    Function callback,
    Function errorCallback,
  }) {
    Map args = {
      'skip': 0,
    };

    ApolloRequestUtil.visitorTypes(
      (response) {
        // 请求成功回调
        List<VisitorTypeModel> _visitorTypes = List<VisitorTypeModel>();
        var _result = response['data']['visitorTypes']['items'];
        for (var value in _result) {
          _visitorTypes.add(VisitorTypeModel.fromJson(value));
        }
        if (callback != null) {
          callback(_visitorTypes);
        }
      },
      args: args,
      errorCallback: (errMsg) {
        if (errorCallback != null) {
          errorCallback(errMsg);
        }
      },
    );
  }
}
